package com.shimao.celnet.payment.controller.apinotcheck;

import com.shimao.celnet.payment.config.ConstantConfig;
import com.shimao.celnet.payment.form.IAppInterfaceForm;
import com.shimao.celnet.payment.form.PPayForm;
import com.shimao.celnet.payment.model.PPayDetail;
import com.shimao.celnet.payment.util.HttpSendPostUtil;
import com.shimao.celnet.payment.util.SignCheckUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.util.TreeMap;

/**
 * 支付平台-->外部系统
 * 2017/12/14
 * christ
 */

@RestController
@Service
public class CallOut_outPayRetInfoOutController {

    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    private HttpSendPostUtil httpSendPostUtil;

    @Autowired
    private ConstantConfig constantConfig;
    /**
     * 通知物业计费系统
     * 物业计费系统:
     * token URL：http://118.31.9.123/apiAccessToken
     * url: http://test.smwy.huyuezheng.cn/api/fee/payment/paymentresult_out
     * username = "api_mj";
     * password = "4D99B85B749100099FA5C0538E1AC4B7";
     */

    public void outPayRetInfoOutToWY(TreeMap<String, String> params,PPayForm pPayFormResult) throws Exception {
        /**
         * 物业计费的接口验证规则
         * 只接受来自物业的费用
         */
        String nonce = String.valueOf(System.currentTimeMillis());//随机字符串
        String URL = constantConfig.getWyTokenURL()
                +"?username="+ constantConfig.getWyUserName()
                + "&password=" + SignCheckUtil.getWySign(nonce,constantConfig.getWyUserName(),constantConfig.getWyPassword())
                + "&nonce=" + nonce;
        String result = httpSendPostUtil.sendPost(URL,pPayFormResult.getAppKey(),pPayFormResult.getInterfaceId());
        String token = JSONObject.fromObject(result).getString("token");
        //给物业推送消息 如果业务类型里面包含pty则必定是物业费：pty-101支付业务类型:pty-101：物业缴费；pty-102：物业预缴费；
        String ret = httpSendPostUtil.sendPost(constantConfig.getWyReturnURL(), returnJson(params,pPayFormResult,token),token,pPayFormResult.getAppKey(),pPayFormResult.getInterfaceId());
        System.out.println("========outPayRetInfoOutToWY=========="+ret);
    }

    /**
     * 通知NotifyURL的系统
     */
    public void outPayRetInfoOutFromReq(TreeMap<String, String> params,PPayForm pPayFormResult,IAppInterfaceForm iAppInterfaceForm,String token) throws Exception {
        logger.info("======================》通知路径:"+iAppInterfaceForm.getRequestUrl());
        logger.info("======================》通知app_key系统:"+pPayFormResult.getAppKey());
        logger.info("======================》请求报文:"+returnJson(params,pPayFormResult,token).toString());
        String ret = httpSendPostUtil.sendPost(iAppInterfaceForm.getRequestUrl(), returnJson(params,pPayFormResult,token),pPayFormResult.getAppKey(),pPayFormResult.getInterfaceId());
        System.out.println("========outPayRetInfoFromReq=========="+ret);
        logger.info("======================》返回报文："+ret);
    }

    private JSONObject returnJson(TreeMap<String, String> params,PPayForm pPayFormResult,String token) throws Exception {
        //拼接json串
        JSONObject jsonParam = new JSONObject();
        JSONArray array = new JSONArray();
        String receivableId = null;
        String bRemark = null;
        String totalReceivableAmount = null;

        //把多个订单详情凭借传给请求系统
        for (PPayDetail bill : pPayFormResult.getPayDetailList()) {
            jsonParam.put("receivableId", bill.getExsysDetailId());//必须填s
            receivableId = bill.getExsysDetailId()==null?null:bill.getExsysDetailId();
            jsonParam.put("bRemark", bill.getRemark());//必须填
            bRemark =  bill.getRemark()==null?null: bill.getRemark();
            jsonParam.put("totalReceivableAmount", bill.getAmount());//必须填
            totalReceivableAmount =  bill.getAmount()==null?null:bill.getAmount();
            array.add(jsonParam);
        }
        JSONObject object = new JSONObject();
        //注释中加 * 的标识返回参数中必填
        object.put("paymentId", pPayFormResult.getGuid());//支付平台的支付订单ID
        object.put("estateId", pPayFormResult.getEstateSfGuid());//小区的SFID
        object.put("estateName", pPayFormResult.getEstateName());//小区名称
        object.put("houseId", pPayFormResult.getHourceSfGuid());//房源的SFID
        object.put("houseName", pPayFormResult.getHourceName());//房源名称
        object.put("userid", pPayFormResult.getPayUserSfGuid());//用户的SFID
        object.put("userName", pPayFormResult.getPayUserName());//用户名称  *
        object.put("cusorderid", params.get("cusorderid"));//商户订单号
        object.put("appid", params.get("appid"));//应用ID：通联支付平台分配的APPID *
        object.put("cusid", params.get("cusid"));//商户ID：通联支付平台分配的商户号 *
        object.put("pOrderType", pPayFormResult.getBusinessType());//支付业务类型:pty-101：物业缴费；pty-102：物业预缴费；mal-101：商城购买付款 ：park-101：停车缴费  *
        object.put("pType", pPayFormResult.getPayType());//缴费方式（选项：A01支付宝，A02微信，A03银联) *
        object.put("trxcode", params.get("trxcode"));//交易类型：VSP511 : 支付宝支付
        object.put("trxamt", params.get("trxamt"));//交易金额（以分为单位） *
        object.put("trxdate", params.get("trxdate"));//交易请求日期：yyyyMMdd *
        object.put("paytime", params.get("paytime"));//交易完成日期：yyyyMMddHHmmss *
        object.put("trxstatus", params.get("trxstatus"));//交易状态：0000:交易成功；3045:交易超时；3008:余额不足；3999:交易失败；2008:交易处理中；3050:交易已撤销； *
        object.put("trxid", params.get("trxid"));//账单流水号，通联内唯一，用于查询账单 *
        object.put("acct", params.get("acct")); //支付人帐号:例如:微信支付的openid支付宝平台的user_id 如果信息为空,则默认填写000000
        object.put("trxreserved", params.get("trxreserver"));//payment-140_外部付款申请j接口：pRemark字段缴费说明：支付账单编号+名称，多个名称用；分隔，例如：1001_物业费；3008_水费；BH173_冰箱；TCL23_空调
        object.put("chnltrxid", params.get("chnltrxid"));//渠道交易单号:如支付宝,微信平台订单号
        object.put("paymentList", array);
        //生成签名：把所有数据进行拼接，然后在数据的最前面的最后面加上token进行一次md5加密
        TreeMap<String,String> signMap = new TreeMap<String,String>();
        signMap.put("paymentId",pPayFormResult.getGuid());
        signMap.put("trxamt",params.get("trxamt"));
        String sign = SignCheckUtil.postSign(signMap, token);
        //换成新的签名
        object.put("sign", sign);
        return object;
    }
}
